package com.zzh.lib.player;


import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by zzh on 2024/12/17.
 *
 * @date: 2024/12/17 17:54
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.lib.player
 */
public class PCMPlayer {
    private static final int BUFFER_SIZE = 2048;

    private void play(File item) {
        int streamType = AudioManager.STREAM_MUSIC;
        int simpleRate = 44100;
        int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        int mode = AudioTrack.MODE_STREAM;

        int minBufferSize = AudioTrack.getMinBufferSize(simpleRate, channelConfig, audioFormat);

        AudioTrack audioTrack = new AudioTrack(streamType, simpleRate, channelConfig, audioFormat,

                Math.max(minBufferSize, BUFFER_SIZE), mode);
        audioTrack.play();
        byte[] mBuffer = new byte[minBufferSize];
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(item);
            int read;
            while ((read = inputStream.read(mBuffer)) > 0) {
                audioTrack.write(mBuffer, 0, read);
            }
            audioTrack.stop();
            audioTrack.release();
        } catch (RuntimeException | IOException e) {
            Log.e("PCMPlayer", e.getLocalizedMessage());
        }
    }
}
